'use client';

import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { useRouter } from 'next/navigation';
import {
  ArrowLeft,
  Star,
  Clock,
  CheckCircle,
  XCircle,
  Lightbulb,
  RotateCcw,
  Trophy,
  Target
} from 'lucide-react';

interface Question {
  id: string;
  content: string;
  options: string[];
  correctAnswer: number;
  explanation: string;
  hint: string;
  difficulty: number;
  topicId: string;
  topicName: string;
}

interface DailyPracticeSession {
  questions: Question[];
  currentIndex: number;
  answers: (number | null)[];
  showHint: boolean[];
  completed: boolean;
  score: number;
}

export default function DailyPracticePage() {
  const [session, setSession] = useState<DailyPracticeSession | null>(null);
  const [loading, setLoading] = useState(true);
  const [showResult, setShowResult] = useState(false);
  const [selectedAnswer, setSelectedAnswer] = useState<number | null>(null);
  const [showExplanation, setShowExplanation] = useState(false);
  
  const router = useRouter();

  useEffect(() => {
    initializeDailyPractice();
  }, []);

  async function initializeDailyPractice() {
    try {
      // 检查用户登录状态
      const response = await fetch('/api/auth/me', {
        credentials: 'include'
      });

      if (!response.ok) {
        router.push('/auth/login');
        return;
      }

      // 检查今天是否已经完成每日练习
      const today = new Date().toISOString().split('T')[0];

      // 使用本地存储检查
      const completedToday = localStorage.getItem(`daily_practice_${today}`);
      if (completedToday) {
        const sessionData = JSON.parse(completedToday);
        setShowResult(true);
        setSession({
          questions: [],
          currentIndex: 0,
          answers: [],
          showHint: [],
          completed: true,
          score: sessionData.score
        });
        setLoading(false);
        return;
      }

      // 生成新的每日练习题目
      await generateDailyQuestions();
      
    } catch (error) {
      console.error('初始化每日练习失败:', error);
    } finally {
      setLoading(false);
    }
  }

  async function generateDailyQuestions() {
    try {
      // 这里应该从数据库获取题目，现在使用模拟数据
      const mockQuestions: Question[] = [
        {
          id: '1',
          content: '小明有15个苹果，小红有9个苹果，小明比小红多几个苹果？',
          options: ['4个', '5个', '6个', '7个'],
          correctAnswer: 2,
          explanation: '小明有15个苹果，小红有9个苹果，所以小明比小红多 15 - 9 = 6个苹果。',
          hint: '用减法计算：小明的苹果数 - 小红的苹果数',
          difficulty: 1,
          topicId: 'basic-calculation',
          topicName: '基础计算'
        },
        {
          id: '2',
          content: '一个长方形的长是8厘米，宽是5厘米，它的周长是多少厘米？',
          options: ['26厘米', '24厘米', '28厘米', '30厘米'],
          correctAnswer: 0,
          explanation: '长方形的周长公式是：周长 = 2 × (长 + 宽) = 2 × (8 + 5) = 2 × 13 = 26厘米。',
          hint: '长方形周长 = 2 × (长 + 宽)',
          difficulty: 2,
          topicId: 'geometry',
          topicName: '几何图形'
        },
        {
          id: '3',
          content: '鸡兔同笼，共有头20个，脚54只，问鸡有多少只？',
          options: ['13只', '12只', '11只', '10只'],
          correctAnswer: 0,
          explanation: '设鸡有x只，兔有(20-x)只。根据脚的数量：2x + 4(20-x) = 54，解得x = 13。所以鸡有13只。',
          hint: '假设全是鸡，那么应该有40只脚，实际多了14只脚，每只兔子比鸡多2只脚',
          difficulty: 3,
          topicId: 'logic-reasoning',
          topicName: '逻辑推理'
        }
      ];

      const newSession: DailyPracticeSession = {
        questions: mockQuestions,
        currentIndex: 0,
        answers: new Array(mockQuestions.length).fill(null),
        showHint: new Array(mockQuestions.length).fill(false),
        completed: false,
        score: 0
      };

      setSession(newSession);
    } catch (error) {
      console.error('生成每日题目失败:', error);
    }
  }

  function handleAnswerSelect(answerIndex: number) {
    if (!session || showExplanation) return;

    setSelectedAnswer(answerIndex);
    
    const newAnswers = [...session.answers];
    newAnswers[session.currentIndex] = answerIndex;
    
    setSession({
      ...session,
      answers: newAnswers
    });
  }

  function handleSubmitAnswer() {
    if (!session || selectedAnswer === null) return;

    setShowExplanation(true);
  }

  function handleNextQuestion() {
    if (!session) return;

    if (session.currentIndex < session.questions.length - 1) {
      // 下一题
      setSession({
        ...session,
        currentIndex: session.currentIndex + 1
      });
      setSelectedAnswer(session.answers[session.currentIndex + 1]);
      setShowExplanation(false);
    } else {
      // 完成练习
      finishPractice();
    }
  }

  function finishPractice() {
    if (!session) return;

    const correctCount = (session.answers as (number | null)[]).reduce((count: number, answer, index) => {
      return count + (answer === session.questions[index].correctAnswer ? 1 : 0);
    }, 0);

    const finalScore = Math.round((correctCount / session.questions.length) * 100);

    setSession({
      ...session,
      completed: true,
      score: finalScore
    });
    setShowResult(true);

    // 保存练习结果到数据库
    savePracticeResult(finalScore, correctCount);
  }

  async function savePracticeResult(score: number, correctCount: number) {
    try {
      const today = new Date().toISOString().split('T')[0];

      // 保存到本地存储
      const sessionData = {
        score,
        correct_answers: correctCount,
        total_questions: session?.questions.length || 0,
        completed: true,
        completed_at: new Date().toISOString()
      };
      localStorage.setItem(`daily_practice_${today}`, JSON.stringify(sessionData));
    } catch (error) {
      console.error('保存练习结果失败:', error);
    }
  }

  function toggleHint() {
    if (!session) return;

    const newShowHint = [...session.showHint];
    newShowHint[session.currentIndex] = !newShowHint[session.currentIndex];
    
    setSession({
      ...session,
      showHint: newShowHint
    });
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center">
        <div className="glassmorphism p-8 rounded-2xl">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">准备每日练习中...</p>
        </div>
      </div>
    );
  }

  if (!session) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center">
        <div className="glassmorphism p-8 rounded-2xl text-center">
          <XCircle className="w-16 h-16 text-red-400 mx-auto mb-4" />
          <h3 className="text-xl font-semibold text-gray-600 mb-2">加载失败</h3>
          <p className="text-gray-500 mb-4">无法加载每日练习</p>
          <button
            onClick={() => router.back()}
            className="glassmorphism-button px-6 py-2 rounded-lg"
          >
            返回
          </button>
        </div>
      </div>
    );
  }

  if (showResult) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50">
        <nav className="glassmorphism-nav sticky top-0 z-50 backdrop-blur-md bg-white/10 border-b border-white/20">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex justify-between items-center h-16">
              <div className="flex items-center space-x-4">
                <button
                  onClick={() => router.push('/dashboard')}
                  className="p-2 rounded-lg hover:bg-white/20 transition-colors"
                >
                  <ArrowLeft className="w-5 h-5 text-gray-600" />
                </button>
                <h1 className="text-2xl font-bold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">
                  每日练习完成
                </h1>
              </div>
            </div>
          </div>
        </nav>

        <div className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            className="glassmorphism p-8 rounded-2xl text-center"
          >
            <Trophy className="w-20 h-20 text-yellow-500 mx-auto mb-6" />
            <h2 className="text-3xl font-bold text-gray-800 mb-4">
              今日练习完成！
            </h2>
            <div className="text-6xl font-bold text-indigo-600 mb-4">
              {session.score}分
            </div>
            <p className="text-gray-600 mb-8">
              恭喜你完成了今天的练习，继续保持！
            </p>
            
            <div className="flex justify-center space-x-4">
              <button
                onClick={() => router.push('/dashboard')}
                className="glassmorphism-button px-6 py-3 rounded-lg font-medium"
              >
                返回首页
              </button>
              <button
                onClick={() => router.push('/practice/free')}
                className="glassmorphism-button px-6 py-3 rounded-lg font-medium"
              >
                自由练习
              </button>
            </div>
          </motion.div>
        </div>
      </div>
    );
  }

  const currentQuestion = session.questions[session.currentIndex];
  const progress = ((session.currentIndex + 1) / session.questions.length) * 100;

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50">
      {/* 导航栏 */}
      <nav className="glassmorphism-nav sticky top-0 z-50 backdrop-blur-md bg-white/10 border-b border-white/20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center space-x-4">
              <button
                onClick={() => router.back()}
                className="p-2 rounded-lg hover:bg-white/20 transition-colors"
              >
                <ArrowLeft className="w-5 h-5 text-gray-600" />
              </button>
              <div className="flex items-center space-x-2">
                <Star className="w-6 h-6 text-yellow-500" />
                <h1 className="text-2xl font-bold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">
                  每日练习
                </h1>
              </div>
            </div>
            <div className="text-sm text-gray-600">
              {session.currentIndex + 1} / {session.questions.length}
            </div>
          </div>
        </div>
      </nav>

      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 进度条 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="glassmorphism p-4 rounded-2xl mb-8"
        >
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium text-gray-600">练习进度</span>
            <span className="text-sm font-medium text-indigo-600">{Math.round(progress)}%</span>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-2">
            <motion.div
              className="bg-gradient-to-r from-indigo-500 to-purple-500 h-2 rounded-full"
              initial={{ width: 0 }}
              animate={{ width: `${progress}%` }}
              transition={{ duration: 0.5 }}
            />
          </div>
        </motion.div>

        {/* 题目卡片 */}
        <motion.div
          key={session.currentIndex}
          initial={{ opacity: 0, x: 50 }}
          animate={{ opacity: 1, x: 0 }}
          className="glassmorphism p-8 rounded-2xl mb-8"
        >
          <div className="flex items-center justify-between mb-6">
            <div className="flex items-center space-x-2">
              <span className="px-3 py-1 bg-indigo-100 text-indigo-700 rounded-full text-sm font-medium">
                {currentQuestion.topicName}
              </span>
              <span className="px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-sm font-medium">
                难度 {currentQuestion.difficulty}
              </span>
            </div>
            <button
              onClick={toggleHint}
              className="p-2 rounded-lg hover:bg-white/20 transition-colors"
              title="提示"
            >
              <Lightbulb className={`w-5 h-5 ${session.showHint[session.currentIndex] ? 'text-yellow-500' : 'text-gray-400'}`} />
            </button>
          </div>

          <h2 className="text-xl font-semibold text-gray-800 mb-6">
            {currentQuestion.content}
          </h2>

          {/* 提示 */}
          {session.showHint[session.currentIndex] && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-6"
            >
              <div className="flex items-start space-x-2">
                <Lightbulb className="w-5 h-5 text-yellow-500 mt-0.5" />
                <p className="text-yellow-800">{currentQuestion.hint}</p>
              </div>
            </motion.div>
          )}

          {/* 选项 */}
          <div className="space-y-3 mb-6">
            {currentQuestion.options.map((option, index) => (
              <button
                key={index}
                onClick={() => handleAnswerSelect(index)}
                disabled={showExplanation}
                className={`w-full p-4 rounded-lg text-left transition-all ${
                  selectedAnswer === index
                    ? showExplanation
                      ? index === currentQuestion.correctAnswer
                        ? 'bg-green-100 border-2 border-green-500 text-green-800'
                        : 'bg-red-100 border-2 border-red-500 text-red-800'
                      : 'bg-indigo-100 border-2 border-indigo-500 text-indigo-800'
                    : showExplanation && index === currentQuestion.correctAnswer
                    ? 'bg-green-100 border-2 border-green-500 text-green-800'
                    : 'bg-white/50 border border-white/20 hover:bg-white/70'
                }`}
              >
                <div className="flex items-center space-x-3">
                  <div className={`w-6 h-6 rounded-full border-2 flex items-center justify-center text-sm font-medium ${
                    selectedAnswer === index
                      ? showExplanation
                        ? index === currentQuestion.correctAnswer
                          ? 'border-green-500 bg-green-500 text-white'
                          : 'border-red-500 bg-red-500 text-white'
                        : 'border-indigo-500 bg-indigo-500 text-white'
                      : showExplanation && index === currentQuestion.correctAnswer
                      ? 'border-green-500 bg-green-500 text-white'
                      : 'border-gray-300'
                  }`}>
                    {String.fromCharCode(65 + index)}
                  </div>
                  <span>{option}</span>
                  {showExplanation && selectedAnswer === index && index !== currentQuestion.correctAnswer && (
                    <XCircle className="w-5 h-5 text-red-500 ml-auto" />
                  )}
                  {showExplanation && index === currentQuestion.correctAnswer && (
                    <CheckCircle className="w-5 h-5 text-green-500 ml-auto" />
                  )}
                </div>
              </button>
            ))}
          </div>

          {/* 解析 */}
          {showExplanation && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6"
            >
              <h4 className="font-medium text-blue-800 mb-2">解析：</h4>
              <p className="text-blue-700">{currentQuestion.explanation}</p>
            </motion.div>
          )}

          {/* 操作按钮 */}
          <div className="flex justify-between">
            <div></div>
            {!showExplanation ? (
              <button
                onClick={handleSubmitAnswer}
                disabled={selectedAnswer === null}
                className={`px-6 py-3 rounded-lg font-medium transition-all ${
                  selectedAnswer !== null
                    ? 'glassmorphism-button hover:scale-105'
                    : 'bg-gray-200 text-gray-400 cursor-not-allowed'
                }`}
              >
                提交答案
              </button>
            ) : (
              <button
                onClick={handleNextQuestion}
                className="glassmorphism-button px-6 py-3 rounded-lg font-medium hover:scale-105 transition-transform"
              >
                {session.currentIndex < session.questions.length - 1 ? '下一题' : '完成练习'}
              </button>
            )}
          </div>
        </motion.div>
      </div>
    </div>
  );
}
